/*
 * # iohao.com . 渔民小镇
 * Copyright (C) 2021 - 2022 double joker （262610965@qq.com） . All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.iohao.game.simulation.client.controller;

import com.iohao.game.common.kit.StrKit;
import com.iohao.game.simulation.client.ClientSimulation;
import com.iohao.game.simulation.client.config.ClientSimulationConfig;
import com.iohao.game.simulation.client.socket.ClientExternalMessage;
import com.iohao.game.simulation.client.socket.IoGameClientSocket;
import com.iohao.game.simulation.client.socket.IoGameClientSocketManager;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.ServerEndpoint;
import org.noear.solon.core.message.Listener;
import org.noear.solon.core.message.Message;
import org.noear.solon.core.message.Session;

/**
 * ws://localhost:18080/client
 *
 * @author 渔民小镇
 * @date 2022-11-01
 */
@Slf4j
@ServerEndpoint(path = "/client")
public class WebClientSocketListener implements Listener {
    @Override
    public void onOpen(Session session) {

        String ioGameWsUrl = session.param("ioGameWsUrl");
        if (StrKit.isEmpty(ioGameWsUrl)) {
            // 默认不填写的游戏对外服连接地址
            ioGameWsUrl = ClientSimulationConfig.me().getIoGameWsUrl();
        }

        String sessionId = session.sessionId();
        IoGameClientSocket clientSocket = IoGameClientSocket.create(ioGameWsUrl, session);
        IoGameClientSocketManager.me().mapping(sessionId, clientSocket);

        session.attrSet("clientSocket", clientSocket);
        ClientSimulation.sessionId = sessionId;
    }

    @Override
    public void onMessage(Session session, Message message) {

        // 解析 message 为 ClientExternalMessage
        ClientExternalMessage clientExternalMessage = ClientExternalMessage.parse(message);

        // 得到 IoGameClientSocket 连接对象
        IoGameClientSocket clientSocket = (IoGameClientSocket) session.attr("clientSocket");

        int loop = 1;
        log.info("模拟工具接收消息入口，loop : {}", loop);
        // 将消息发送到游戏对外服
        for (int i = 0; i < loop; i++) {
            clientSocket.send(clientExternalMessage);
        }
    }

    @Override
    public void onClose(Session session) {
        log.info("有客户端链关了!");
    }
}
